using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Navigation;
using Microsoft.SharePoint.Administration;
using System.Collections.Generic;

namespace ECTSExtension {
  public class FeatureReceiver : SPFeatureReceiver {

      private const string PATH = "_layouts/ECTSExtension/ExternalUserRequest.aspx";

    public override void FeatureActivated(SPFeatureReceiverProperties properties) {
        SPWebApplication webApp = null;
        
        if (properties.Feature.Parent is SPSite)
        {
            SPSite spSite = properties.Feature.Parent as SPSite;
            webApp = spSite.WebApplication;
        }
        else if (properties.Feature.Parent is SPWebApplication)
        {
            webApp = properties.Feature.Parent as SPWebApplication;
        }

        webApp.WebConfigModifications.Add(Modification);
        webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
        webApp.Update();
    }

    public override void FeatureDeactivating(SPFeatureReceiverProperties properties) {
        SPWebApplication webApp = null;

        if (properties.Feature.Parent is SPSite)
        {
            SPSite spSite = properties.Feature.Parent as SPSite;
            webApp = spSite.WebApplication;
        }
        else if (properties.Feature.Parent is SPWebApplication)
            webApp = properties.Feature.Parent as SPWebApplication;

        webApp.WebConfigModifications.Remove(Modification);
        webApp.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
        webApp.Update();
    }

    public override void FeatureInstalled(SPFeatureReceiverProperties properties) { /* no op */}
    public override void FeatureUninstalling(SPFeatureReceiverProperties properties) { /* no op */}

      private SPWebConfigModification Modification
      {
          get
          {
              SPWebConfigModification mod = new SPWebConfigModification(string.Format("location[@path='{0}']", PATH),
                  "configuration");
              mod.Owner = this.GetType().ToString();
              mod.Sequence = 0;
              mod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
              mod.Value = string.Format("<location path='{0}'><system.web><authorization><allow users='?' /></authorization></system.web></location>",
                  PATH);
              return mod;
          }
      }
  }
}
